#include <cmath>
#include <string>
#include <vector>
#include <fstream>
#include <cstring>
#include <sstream>
#include <iostream>

using namespace std;

const double EPS = 1e-8;
const int IMAGE_THEME_COUNT = 139;
const int MUSIC_THEME_COUNT = 77;
const int DOC_COUNT = 4043523;

double dis[IMAGE_THEME_COUNT][MUSIC_THEME_COUNT];
vector<pair<int, double> > image_index[IMAGE_THEME_COUNT];
vector<pair<int, double> > music_index[MUSIC_THEME_COUNT];

double v1[DOC_COUNT];
double v2[DOC_COUNT];

double GetCosDistance(int a, int b)
{
    memset(v1, 0, sizeof v1);
    memset(v2, 0, sizeof v2);
    for (int i = 0; i < image_index[a].size(); ++i) {
        v1[image_index[a][i].first] += image_index[a][i].second;
    }
    for (int i = 0; i < music_index[b].size(); ++i) {
        v2[music_index[b][i].first] += music_index[b][i].second;
    }

    double len1 = 0;
    double len2 = 0;
    double val = 0;

    for (int i = 0; i < DOC_COUNT; ++i) {
        len1 += v1[i] * v1[i];
        len2 += v2[i] * v2[i];
        val += v1[i] * v2[i];
    }

    len1 = sqrt(len1);
    len2 = sqrt(len2);
    if (len1 * len2 < EPS) {
        return 0;
    }

    return val / (len1 * len2);
}

int main(int argc, const char *argv[])
{
    ifstream fin_image("image_theme_ESA_index");
    ifstream fin_music("music_theme_ESA_index");
    ofstream fout("vector_distance");

    string line;
    int id;
    double val;
    int cnt = 0;

    while (getline(fin_image, line)) {
        stringstream ss(line);
        while (ss >> id >> val) {
            image_index[cnt].push_back(make_pair(id, val));
        }
        ++cnt;
    }

    cnt = 0;
    while (getline(fin_music, line)) {
        stringstream ss(line);
        while (ss >> id >> val) {
            music_index[cnt].push_back(make_pair(id, val));
        }
        ++cnt;
    }

    for (int i = 0; i < IMAGE_THEME_COUNT; ++i) {
        for (int j = 0; j < MUSIC_THEME_COUNT; ++j) {
            fout << GetCosDistance(i, j) << ' ';
        }
        fout << endl;
    }

    return 0;
}
